<template>
  <div class="dropdown-item flex-item flex-wrap flex-middle flex-center van-dropdown-menu__bar">
		<span class="dropdown-item-show" @click="opend">
			{{ getText(checked) }} <uni-icons :type="show ? 'up' : 'down'" color="#666" size="12"></uni-icons>
		</span>
    <div></div>
    <div :class="['dropdown-popup', show && 'active' || '', top && 'top' || '']" @click="closed">
      <div class="dropdown-popup-body">
        <div class="dropdown-popup-list" v-if="options.length">
          <div class="dropdown-popup-list-item"
               v-for="(item, index) in options"
               :key="index"
               :class="{active: item.value === checked}"
               @click="onConfirm(item.value)">{{ item.text }}
          </div>
        </div>
        <slot/>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'checked',
    event: 'change'
  },
  data() {
    return {
      show: false
    }
  },
  props: {
    checked: {
      type: [String, Number, Array],
      default: ''
    },
    options: {
      type: Array,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    top: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    opend() {
      if (this.show) {
        this.closed()
        return
      }
      uni.$emit('closeDropdown')
      this.show = true
      uni.$on('closeDropdown', () => {
        this.closed()
      })
    },
    closed() {
      uni.$off('closeDropdown')
      this.show = false
    },
    getText(val) {
      let ob = this.options.find(e => e.value == val)
      return ob ? ob.text : this.title || this.placeholder
    },
    onConfirm(date) {
      this.$emit('change', date)
    }
  }
}
</script>

<style lang="scss" scoped>
.dropdown-item {
  text-align: center;
  height: 50px !important;
  .dropdown-item-show {
    font-size: 28rpx;
  }

  .uni-icons {
    margin-left: 8rpx;
  }

  .dropdown-popup {
    position: fixed;
    left: 0;
    top: -100vh;
    width: 100%;
    height: 100vh;
    background: rgba(0, 0, 0, 0.7);
    transition: all 0.2s;
    opacity: 0;
    z-index: -1;

    &.active {
      opacity: 1;
      z-index: 99;
      top: auto;
    }

    &.top.active {
      padding-top: var(--status-bar-height);
      top: 44px;
    }
  }

  .dropdown-popup-body {
    width: 100%;
    padding: 6px 0;
    background: #fff;
  }

  .dropdown-popup-list-item {
    font-size: 26rpx;
    padding: 6px 15px;
    text-align: left;
    color: #333;

    &.active {
      color: var(--color);
    }
  }
}
</style>